//
//  CWSportTrackingModel.m
//  大神专制黑马行
//
//  Created by chenWei on 2017/5/11.
//  Copyright © 2017年 陈伟. All rights reserved.
//

#import "CWSportTrackingModel.h"


@interface CWSportTrackingModel ()

//开始位置
@property(nonatomic, strong) CLLocation *startLocation;

//轨迹线条数组
@property(nonatomic, strong) NSMutableArray<CWSportTrackingLine *> *sportTrackingLineArr;


@end

@implementation CWSportTrackingModel

/**
 初始化构造方法

 @param sportType 运动类型
 @return 返回初始化对象
 */
- (instancetype)initWithSportType:(SportType)sportType
{
    return [self initWithSportType:sportType SportState:SportStateContinue];
}

- (instancetype)initWithSportType:(SportType)sportType SportState:(SportState)sportState
{
    self = [super init];
    //设置启动默认运动状态
    self.sportState = SportStateContinue;
    self.sportType = sportType;
    
    _sportTrackingLineArr = [NSMutableArray array];
    return self;
}

//重写运动状态的 setter 方法
- (void)setSportState:(SportState)sportState
{
    _sportState = sportState;
    
    //如果当前点击按钮为暂停状态，那么就把开始位置置为 nil，等下一次点击继续的时候，把当前位置为起始位置。
    if (sportState == SportStatePause) {
        self.startLocation = nil;
    }
    
}


//大头针的 getter 方法
- (UIImage *)image
{
    UIImage *image;
    switch (self.sportType) {
        case SportTypeRide:
            image= [UIImage imageNamed:@"map_annotation_bike.png"];
            break;
        case SportTypeRun:
            image= [UIImage imageNamed:@"map_annotation_run.png"];
            break;
        case SportTypeWalk:
            image= [UIImage imageNamed:@"map_annotation_walk.png"];
            break;
        default:
            break;
    }

    return image;
}


#pragma mark - 返回 GPS 信号
- (HMSportGpsSignalState) gpsSignalStateWithLocation:(CLLocation *)location
{
    HMSportGpsSignalState state;
    
    //1.通过location的水平精度来判断gps信号
    if (location.horizontalAccuracy < 0) {
        state = HMSportGpsSignalStateClose;
    } else if (location.horizontalAccuracy > 163) {
        state = HMSportGpsSignalStateBad;
    } else if (location.horizontalAccuracy > 48) {
        state = HMSportGpsSignalStateNormal;
    } else {
        state = HMSportGpsSignalStateGood;
    }
    
    //信号变更
    if (state != _sportGpsSignalState) {
        //保存信号
        _sportGpsSignalState = state;
        
        //发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:kGPSSignalChangeNotification object:nil userInfo:@{@"key":@(state)}];
        
    }
    
    return state;
}



//MARK: - 绘制轨迹线条
- (CWSportPolyline *)drawPolylineWithLocation:(CLLocation *)location
{
    //时间优化法 timeStamp 指的是卫星找到位置的时间
//    if ([[NSDate date] timeIntervalSinceDate:location.timestamp] >= 2) {
//        //如果卫星定位的时间过长，我们认为这主要是由于GPS信号误差太大导致，不进行轨迹计算
//        return nil;
//    }
    
    //速度优化法
    //判断用户的速度是否大于0，如果不大于0就表示为静止状态, 不需要绘制轨迹,大大提高了 App 的性能消耗
    if (location.speed <= 0) {
        return nil;
    }
    
    //如果运动状态不是继续，那么就不绘制线条
    if (self.sportState != SportStateContinue) {
        return nil;
    }
    
    //判断起点位置是否有值，没有起点位置就为开始位置
    if (self.startLocation == nil) {
        self.startLocation = location;
        return nil;
    }
    
    //如果信号强度不好(根据位置变化)，就不绘制轨迹
    if ([self gpsSignalStateWithLocation:location] != HMSportGpsSignalStateGood) {
        return nil;
    }
    
    
    //有起点位置，就进行绘制
    CWSportTrackingLine *trackline = [[CWSportTrackingLine alloc]initWithStartLocation:self.startLocation endLocation:location];
    
    //把轨迹线条保存到数组
    [self.sportTrackingLineArr addObject:trackline];
    
    //NSLog(@"运动总距离：%0.2f  运动时间：%@  运动平均速度：%0.2f km/h  运动最大速度：%0.2f km/h ",self.totalDistance,self.totalTimeStr,self.avgSpeed,self.maxSpeed);
    
    
    //记录当前位置为下一条轨迹线的起始位置
    self.startLocation = location;
    
    //返回轨迹线条模型的折线模型
    return trackline.polyline;
    
}


//运动总距离
- (float)totalDistance
{
    //@：表示kvc返回的是一个NSDecimalNumber对象  sum：求和计算  distance：轨迹线条模型的属性
    return [[self.sportTrackingLineArr valueForKeyPath:@"@sum.distance"] floatValue];
    
}


//运动总时间
- (float)totalTime
{
    return [[self.sportTrackingLineArr valueForKeyPath:@"@sum.time"] floatValue];
}

//运动总时间字符串
- (NSString *)totalTimeStr
{
    int hour = self.totalTime/3600;
    int minute = (int)self.totalTime%3600/60;
    int second = (int)self.totalTime%60;
    return [NSString stringWithFormat:@"%02zd:%02zd:%02zd",hour,minute,second];
}

//运动平均速度
- (float)avgSpeed
{
    return [[self.sportTrackingLineArr valueForKeyPath:@"@avg.speed"] floatValue];
}

//运动最大速度
- (float)maxSpeed
{
    return [[self.sportTrackingLineArr valueForKeyPath:@"@max.speed"] floatValue];
}



@end
